<template>
  <div class="exam-record-page">
    <!-- 搜索区域 -->
    <ElCard class="search-card">
      <div class="search-form">
        <ElSpace wrap>
          <ElInput
            v-model="searchForm.username"
            placeholder="搜索用户名"
            clearable
            style="width: 160px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>

          <ElSelect
            v-model="searchForm.exam_id"
            placeholder="选择考试活动"
            clearable
            style="width: 200px"
          >
            <ElOption
              v-for="exam in examList"
              :key="exam._id"
              :label="exam.exam_name"
              :value="exam._id!"
            />
          </ElSelect>

          <ElSelect
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <ElOption label="进行中" value="in_progress" />
            <ElOption label="已完成" value="completed" />
            <ElOption label="已超时" value="timeout" />
          </ElSelect>

          <ElDatePicker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />

          <ElButton type="primary" :icon="Search" @click="handleSearch">
            搜索
          </ElButton>

          <ElButton @click="handleReset"> 重置 </ElButton>

          <ElButton
            type="danger"
            :disabled="selectedRecords.length === 0"
            :icon="Delete"
            @click="handleBatchDelete"
          >
            批量删除 ({{ selectedRecords.length }})
          </ElButton>

          <ElButton type="success" :icon="Download" @click="handleExport">
            导出记录
          </ElButton>
        </ElSpace>
      </div>
    </ElCard>

    <!-- 表格区域 -->
    <ElCard class="table-card">
      <ElTable
        :data="recordList"
        :loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <ElTableColumn type="selection" width="55" />

        <ElTableColumn prop="user_id.username" label="用户" width="120">
          <template #default="{ row }">
            <div>{{ row.user_id?.username || "未知用户" }}</div>
            <div class="text-secondary">{{ row.user_id?.phone }}</div>
          </template>
        </ElTableColumn>

        <ElTableColumn
          prop="exam_id.exam_name"
          label="考试活动"
          min-width="200"
        >
          <template #default="{ row }">
            <ElLink type="primary" @click="viewExamDetail(row.exam_id?._id)">
              {{ row.exam_id?.exam_name || "未知考试" }}
            </ElLink>
          </template>
        </ElTableColumn>

        <ElTableColumn label="考试时间" width="180">
          <template #default="{ row }">
            <div>开始：{{ formatDate(row.start_time) }}</div>
            <div v-if="row.submit_time" class="text-success">
              完成：{{ formatDate(row.submit_time) }}
            </div>
          </template>
        </ElTableColumn>

        <ElTableColumn label="状态" width="100">
          <template #default="{ row }">
            <ElTag :type="getStatusTagType(row.status) as any">
              {{ getStatusText(row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>

        <ElTableColumn label="成绩" width="120">
          <template #default="{ row }">
            <template v-if="row.status === 'completed'">
              <div class="score-display">
                <span class="score-value">{{ row.user_score || 0 }}</span>
                <span class="score-total">/ {{ row.total_score || 0 }}</span>
              </div>
              <div class="score-percent">
                {{ getScorePercent(row.user_score, row.total_score) }}%
              </div>
            </template>
            <template v-else>
              <span class="text-secondary">--</span>
            </template>
          </template>
        </ElTableColumn>

        <ElTableColumn label="答题统计" width="120">
          <template #default="{ row }">
            <template v-if="row.status === 'completed'">
              <div class="answer-stats">
                <div class="text-success">
                  正确：{{ row.correct_count || 0 }}
                </div>
                <div class="text-danger">错误：{{ row.wrong_count || 0 }}</div>
                <div class="text-secondary">
                  未答：{{ row.unanswered_count || 0 }}
                </div>
              </div>
            </template>
            <template v-else>
              <span class="text-secondary">--</span>
            </template>
          </template>
        </ElTableColumn>

        <ElTableColumn label="用时" width="100">
          <template #default="{ row }">
            <template v-if="row.submit_time">
              {{ getExamDuration(row.start_time, row.submit_time) }}
            </template>
            <template v-else>
              <span class="text-secondary">未完成</span>
            </template>
          </template>
        </ElTableColumn>

        <ElTableColumn label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <ElSpace>
              <ElButton
                type="primary"
                size="small"
                :icon="View"
                @click="viewDetail(row._id)"
              >
                查看详情
              </ElButton>

              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row._id)"
              >
                删除
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <ElPagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>

    <!-- 考试记录详情对话框 -->
    <ElDialog
      v-model="detailDialogVisible"
      title="考试记录详情"
      width="80%"
      :before-close="handleCloseDetail"
    >
      <ExamRecordDetail
        v-if="detailDialogVisible"
        :record-id="selectedRecordId"
        @close="handleCloseDetail"
      />
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";

import {
  ElButton,
  ElCard,
  ElDatePicker,
  ElDialog,
  ElInput,
  ElLink,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElSpace,
  ElTable,
  ElTableColumn,
  ElTag,
} from "element-plus";

import { useCommonStore } from "@/store/common";
import { Delete, Download, Search, View } from "@element-plus/icons-vue";
import type { IExam, IExamRecord } from "@shared/types/exam";

import { apiList } from "../../api/apiList";
import ExamRecordDetail from "./components/ExamRecordDetail.vue";

const commonStore = useCommonStore();
commonStore.header = "考试记录管理";

// 响应式数据
const loading = ref(false);
const recordList = ref<any[]>([]);
const examList = ref<IExam[]>([]);
const selectedRecords = ref<IExamRecord[]>([]);
const detailDialogVisible = ref(false);
const selectedRecordId = ref("");

// 搜索表单
const searchForm = reactive({
  exam_id: "",
  status: "",
  username: "",
  dateRange: [] as string[],
});

// 分页信息
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
});

// 生命周期
onMounted(() => {
  loadExamList();
  loadRecordList();
});

// 加载考试活动列表
const loadExamList = async () => {
  try {
    const response = await apiList.exam.getExamList({
      page: 1,
    });
    if (response.code === 200) {
      examList.value = response.data.data || [];
    }
  } catch (error) {
    console.error("加载考试活动列表失败:", error);
  }
};

// 加载考试记录列表
const loadRecordList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      exam_id: searchForm.exam_id,
      status: searchForm.status,
      username: searchForm.username,
      start_date: searchForm.dateRange[0] || "",
      end_date: searchForm.dateRange[1] || "",
    };

    const response = await apiList.examRecord.getExamRecordList(params);
    if (response.code === 200) {
      recordList.value = response.data.data || [];
      pagination.total = response.data.total_records || 0;
    }
  } catch (error) {
    console.error("加载考试记录列表失败:", error);
    ElMessage.error("加载考试记录列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadRecordList();
};

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    exam_id: "",
    status: "",
    username: "",
    dateRange: [],
  });
  handleSearch();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  loadRecordList();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadRecordList();
};

// 选择变化
const handleSelectionChange = (selection: IExamRecord[]) => {
  selectedRecords.value = selection;
};

// 查看考试详情
const viewExamDetail = (examId?: string) => {
  if (examId) {
    // 跳转到考试详情页面
    console.log("查看考试详情:", examId);
  }
};

// 查看记录详情
const viewDetail = (recordId: string) => {
  selectedRecordId.value = recordId;
  detailDialogVisible.value = true;
};

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false;
  selectedRecordId.value = "";
};

// 删除单条记录
const handleDelete = async (recordId: string) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这条考试记录吗？此操作不可恢复。",
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await apiList.examRecord.deleteExamRecord(recordId);
    if (response.code === 200) {
      ElMessage.success("删除成功");
      loadRecordList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除考试记录失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRecords.value.length === 0) {
    ElMessage.warning("请先选择要删除的记录");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRecords.value.length} 条记录吗？此操作不可恢复。`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRecords.value.map((record) => record._id!);
    const response = await apiList.examRecord.batchDeleteExamRecords(ids);

    if (response.code === 200) {
      ElMessage.success("批量删除成功");
      loadRecordList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 导出记录
const handleExport = async () => {
  try {
    const params = {
      exam_id: searchForm.exam_id,
      status: searchForm.status,
      username: searchForm.username,
      start_date: searchForm.dateRange[0] || "",
      end_date: searchForm.dateRange[1] || "",
    };

    const response = await apiList.examRecord.exportExamRecords(params);

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement("a");
    link.href = url;
    link.download = `考试记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
    link.click();
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败");
  }
};

// 工具函数
const formatDate = (date: string | Date) => {
  if (!date) return "";
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const getStatusTagType = (status: string) => {
  switch (status) {
    case "completed":
      return "success";
    case "in_progress":
      return "primary";
    case "timeout":
      return "danger";
    default:
      return "info";
  }
};

const getStatusText = (status: string) => {
  switch (status) {
    case "completed":
      return "已完成";
    case "in_progress":
      return "进行中";
    case "timeout":
      return "已超时";
    default:
      return "未知";
  }
};

const getScorePercent = (score?: number, totalScore?: number) => {
  if (!score || !totalScore) return 0;
  return Math.round((score / totalScore) * 100);
};

const getExamDuration = (startTime: string | Date, endTime: string | Date) => {
  const start = new Date(startTime);
  const end = new Date(endTime);
  const duration = Math.floor((end.getTime() - start.getTime()) / 1000 / 60);
  return `${duration}分钟`;
};
</script>

<style scoped>
.exam-record-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-secondary {
  color: #909399;
  font-size: 12px;
}

.text-success {
  color: #67c23a;
  font-size: 12px;
}

.text-danger {
  color: #f56c6c;
  font-size: 12px;
}

.score-display {
  display: flex;
  align-items: center;
  gap: 2px;
}

.score-value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.score-total {
  font-size: 12px;
  color: #909399;
}

.score-percent {
  font-size: 12px;
  color: #67c23a;
  margin-top: 2px;
}

.answer-stats {
  font-size: 12px;
  line-height: 1.4;
}
</style>
